<template>
    <div class="dept-tree-selector">
        <el-tree ref="treeRef" style="max-width: 600px" :props="props" :data="state.data" show-checkbox node-key="id"
            :check-strictly="true" :default-expanded-keys="[deptId]" @check="handleCheck" />
        <div class="footer">
            <el-button @click="cancel">取消</el-button>
            <el-button type="primary" @click="sure">
                确定
            </el-button>
        </div>
    </div>
</template>
<script setup>
import { ref, reactive, onMounted, defineProps } from "vue"
import { authTree } from '@/api/system/dept'
import { useUserStore } from '@/stores/user.js';
import { storeToRefs } from "pinia";
import { ElMessage } from 'element-plus'

const emit = defineEmits(['cancel', 'sure'])
const treeRef = ref(null)
const userStore = useUserStore();
const { deptId } = storeToRefs(userStore)


const props = defineProps({
    selectLast: {
        type: Boolean,
        default: false
    }
})

const state = reactive({
    data: [],
    currentNode: {
        id: undefined,
        label: undefined,
    },
    lastCheckedNodeId: null, // 记录上次选中的节点
})

const getTree = () => {
    authTree().then(data => {
        if (props.selectLast) {
            setLastDisabled(data)
        }
        state.data = data
    })
}

const setLastDisabled = (data) => {
    data.forEach(item => {
        if (item.children && item.children.length > 0) {
            item.disabled = true
            setLastDisabled(item.children)
        } else {
            item.disabled = false
        }
    });
}

const handleCheck = (node, checkedStatus) => {
    if (state.lastCheckedNodeId) {
        treeRef.value.setChecked(state.lastCheckedNodeId, false, false)
    }
    state.lastCheckedNodeId = node.id
    state.currentNode.id = node.id
    state.currentNode.label = node.label
}

const cancel = () => {
    emit("cancel")
}
const sure = () => {
    if (state.currentNode.id == undefined) {
        ElMessage({
            message: '请选择一个部门节点！',
            type: 'warning',
        })
        return
    }
    emit("sure", state.currentNode)
}
onMounted(() => {
    getTree()
})

</script>
<style scoped lang="scss">
.dept-tree-selector {
    .footer {
        margin-top: 20px;
        display: flex;
        justify-content: end;
    }
}
</style>
